﻿from typing import List
import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware  # 引入 CORS中间件模块
from database.token_table import TokenTable
from model.token import Token
from loguru import logger
import math

logger.add(
    sink="./logs/{time:YYYY-MM-DD}.log",
    # format = "{time:HH:mm:ss} {level} {message}",
    level="INFO",
    rotation="00:00",
)

app = FastAPI()
# 设置允许访问的域名
origins = ["*"]  # 也可以设置为"*"，即为所有。

# 设置跨域传参
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,  # 设置允许的origins来源
    allow_credentials=True,
    allow_methods=["*"],  # 设置允许跨域的http方法，比如 get、post、put等。
    allow_headers=["*"],
)  # 允许跨域的headers，可以用来鉴别来源等作用。


def get_table(token_type: int):
    return TokenTable()

# def assign_token(tokens, task_id):
#     if task_id <= 0:
#         logger.warning(f"assign_token: task_id invalid : {task_id}")
#         return tokens
    
#     with hr_tasks_table() as db:
#         task = db.query(task_id)
#         if not task:
#             logger.error(f"assign_token: task_id {task_id} not found")
#             return tokens
        
#         # if task.weight() <= 0:
#         #     logger.info(f"assign_token: weight invalid : {task.weight() }")
#         #     return tokens
        
#         #筛选platform_id相同且status为1的任务
#         tasks = [item for item in db.all() if item.platform_id == task.platform_id and item.status == 1]
        
#         if len(tokens) <= len(tasks):
#             logger.error(f"assign_token: len(tokens) <= len(tasks), {len(tokens)}, {len(tasks)}")
#             return tokens
        
#         token_count = len(tokens)
        
#         #根据权重分配token
#         last_index = 0
#         total_weight = sum([item.get_weight() for item in tasks])
#         for task in tasks:
#             rate = task.get_weight() / total_weight
#             logger.info(f"assign_token1: {task.id}, {last_index}, {rate}, {token_count}")
#             if task.id == task_id:
#                 start_index = last_index
#                 end_index = last_index + round(token_count * rate)
#                 if end_index >= token_count:
#                     end_index = token_count
#                 logger.info(f"assign_token2: {task.id}, {start_index}, {end_index}")
#                 return tokens[start_index:end_index]
#             else:
#                 last_index += round(token_count * rate)

#     logger.error(f"assign_token: not matched task_id, {task_id}")
#     return tokens

@app.get("/api/parktoken/data")
def token_get(token_type: int, second: int = 0, max_used: int = 0, limit: int = 0, task_id: int = 0):
    try:
        with get_table(token_type) as db:
            tokens = db.get_latest(token_type, second, max_used, limit)
        logger.info(
            f"received token get: {token_type}, {second}, {max_used}, {limit}, return {len(tokens)} records"
        )
    except Exception as e:
        logger.exception(f"token get error: {e}")
    return {"code": 0, "count": len(tokens), "data": tokens}


@app.post("/api/parktoken/data")
def token_post(data: dict):
    token = Token().load(data)
    with get_table(token.type) as db:
        index = db.insert(token)
        db.commit()
    logger.info(f"received token count: {len(data)}, return {index}")
    return {"code": 0, "data": index}


@app.post("/api/parktoken/data_list")
def token_post(data: List[dict]):
    token = Token().load(data[0])
    with get_table(token.type) as db:
        for item in data:
            index = db.insert(Token().load(item))
        db.commit()
    logger.info(f"received token count: {len(data)}, return {index}")
    return {"code": 0, "data": index}


@app.get("/api/parktoken/config")
def token_yima():
    with open("config.json", "r") as f:
        config = f.read()
    # logger.info(f"received request /api/parktoken/config, return {config}")
    return {"code": 0, "data": config}


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=4567)
